import {messages} from "share/common";
import React from 'react';
import {  Modal } from 'antd'
import errorMessage from "share/errorMessage";
import startIcon from 'images/mileage-subsidy/start.png'
import endIcon from 'images/mileage-subsidy/end.png'
import pointIcon from 'images/mileage-subsidy/point.png'
import mileageExpenseService from 'containers/mileage-subsidy-expense/mileage-subsidy-expense.service';

class WayPointEdit extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      show: false
    };
  }

  renderMap = () => {
    //异步加载地图库函数文件
    const loadScript = () => {
      //创建script标签
      var script = document.createElement('script');
      //设置标签的type属性
      script.type = 'text/javascript';
      //设置标签的链接地址
      script.src = 'https://map.qq.com/api/js?v=2.exp&key=XLMBZ-VVB3G-AHFQZ-IOCU3-MLGI5-6WFWY&callback=initMap';
      //添加标签到dom
      document.body.appendChild(script);
    };

    window.initMap = () => {
      const { record } = this.props;
      let path = [], polyline, map, center;
      const { start, end, viaPoints } = record;
      try {
        center = new qq.maps.LatLng(((start.lat - '0' + (end.lat - '0')) / 2).toFixed(6), ((start.lng - '0' + (end.lng - '0')) / 2).toFixed(6));
        map = new qq.maps.Map(document.getElementById('mileageMap'), {
          center: center,
          zoom: 13
        });
      }
      catch (e) {
        loadScript();
        return;
      }


      let marker = [
        new qq.maps.Marker({
          position: new qq.maps.LatLng(start.lat, start.lng),
          map: map,
          icon: startIcon,
        }), new qq.maps.Marker({
          position: new qq.maps.LatLng(end.lat, end.lng),
          map: map,
          icon: endIcon,
        })
      ];

      const commonFn = () => {
        polyline = new qq.maps.Polyline({
          path,
          strokeColor: '#4B8DFF',
          strokeWeight: 5,
          editable: false,
          map
        });
      };

      const service = new Promise((resolve, reject) => {
        if (record['attachmentDTO']) {
          mileageExpenseService.getAmapTrack({ 'orderId': record.id })
            .then((res) => {
              if (!res.data) {
                reject(false);
              } else {
                res.data.points.map(item => {
                  path.push(new qq.maps.LatLng(item.location.split(',')[1], item.location.split(',')[0]));
                });
                resolve(true);
              }
            })
            .catch(err => {
              errorMessage(err.response);
              reject(false);
            });
        } else {
          reject(false);
        }
      });

      viaPoints && viaPoints
        .forEach(item => {
          marker.push(
            new qq.maps.Marker({
              position: new qq.maps.LatLng(item.lat, item.lng),
              map: map,
              icon: pointIcon,
            }));
        });

      service
        .then(() => {
          commonFn();
        });
    };
    window.initMap();
  };

  handleMap = (e) => {
    e.stopPropagation();
    this.setState({ visible: true },  this.renderMap);
  };

  onCancel = () => {
    this.setState({ visible: false });
  };


  render() {
    const { className, record } = this.props;
    const { visible } = this.state;
    return (
      <section className={className || ''}>
        <a disabled={record.createdMode === 1001} onClick={this.handleMap}>{messages('mileage-subsidy-expense.key62')/*行程图*/}</a>
        <Modal
          title="行程图"
          visible={visible}
          onCancel={this.onCancel}
          footer={[]}>
          {
            visible && <div id="mileageMap" style={{ height: 300, width: 470 }}/>
          }
        </Modal>
      </section>
    );
  }
}

WayPointEdit.propTypes = {
  record: React.PropTypes.object,
  className: React.PropTypes.string
};

export default WayPointEdit;

